<template>
  <div class="hedge-workbench">
    <!-- 状态监控面板 -->
    <div class="status-panel">
      <el-row :gutter="20">
        <!-- websocket连接状态 -->
        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="flex-center">
              <div class="status-header-title">连接状态</div>
              <div class="status-content">
                <div class="status-indicator">
                  <div
                    class="light"
                    :class="{
                      green: websocketState.isConnected,
                      red:
                        !websocketState.isConnected &&
                        !websocketState.isReconnecting,
                      yellow: websocketState.isReconnecting,
                    }"
                  ></div>
                  <span class="status-text">
                    {{ getConnectionStatusText() }}
                  </span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 水贝金价采集状态 -->
        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="flex-center">
              <div class="status-header-title">水贝金价采集</div>

              <div class="status-content">
                <div class="status-lights-container">
                  <div class="status-lights">
                    <div
                      v-for="i in 5"
                      :key="i"
                      class="status-light"
                      :class="{ active: i <= waterGoldStatus }"
                      :title="`采集点 ${i}`"
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 国际金价采集状态 -->
        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="flex-center">
              <div class="status-header-title">国际金价采集</div>

              <div class="status-content">
                <div class="status-lights-container">
                  <div class="status-lights">
                    <div
                      v-for="i in 5"
                      :key="i"
                      class="status-light"
                      :class="{ active: i <= internationalGoldStatus }"
                      :title="`采集点 ${i}`"
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 交易终端状态 -->
        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="flex-center">
              <div class="status-header-title">交易终端状态</div>

              <div class="status-content">
                <div class="status-indicator">
                  <div
                    class="light"
                    :class="{
                      green: tradingTerminalStatus.isActive,
                      red: !tradingTerminalStatus.isActive,
                      yellow: tradingTerminalStatus.isInitializing,
                    }"
                  ></div>
                  <span class="status-text">
                    {{ getTradingStatusText() }}
                  </span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 对冲模式控制 -->
    <div class="hedge-mode-control">
      <el-card shadow="hover">
        <div class="hedge-mode-header">
          <span class="hedge-mode-title">对冲模式控制</span>
          <el-switch
            v-model="hedgeMode"
            active-value="auto"
            inactive-value="manual"
            active-text="自动"
            inactive-text="手动"
            @change="handleHedgeModeChange"
          >
          </el-switch>
        </div>
      </el-card>
    </div>

    <!-- 金价信息面板 -->
    <div class="price-panel">
      <el-row :gutter="20">
        <!-- 水贝金价 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <div class="price-info">
              <div class="price-item">
                <span class="label">水贝金价:</span>
                <span class="value">¥{{ waterGoldPrice }}</span>
              </div>
              <div class="price-item">
                <span class="label">点差:</span>
                <span class="value">{{ waterGoldSpread }}</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 国际金价 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <div class="price-info">
              <div class="price-item">
                <span class="label">国际金价:</span>
                <span class="value">${{ internationalGoldPrice }}</span>
              </div>
              <div class="price-item">
                <span class="label">点差:</span>
                <span class="value">${{ priceDifference }}</span>
                <span class="cny-value">¥{{ cnyPrice }}</span>
              </div>
              <div class="price-item">
                <span class="label">汇率:</span>
                <span class="value">{{ exchangeRate }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 仓位信息面板 -->
    <div class="position-panel">
      <el-row :gutter="20">
        <!-- 当前仓位 -->
        <el-col :span="8">
          <el-card shadow="hover">
            <div slot="header">
              <span>当前仓位</span>
            </div>
            <div class="position-info">
              <div class="position-item buy">
                <span class="label">买:</span>
                <span class="value">{{ currentPosition.buy }}克</span>
              </div>
              <div class="position-item sell">
                <span class="label">卖:</span>
                <span class="value">{{ currentPosition.sell }}克</span>
              </div>
              <div class="position-item total">
                <span class="label">库存:</span>
                <span class="value">{{ currentPosition.total }}克</span>
              </div>
              <div class="position-item net">
                <span class="label">净头寸:</span>
                <span class="value">{{ currentPosition.netPosition }}元</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 对冲仓位 -->
        <el-col :span="8">
          <el-card shadow="hover">
            <div slot="header">
              <span>对冲仓位</span>
            </div>
            <div class="hedge-position-info">
              <div class="position-item buy">
                <span class="label">买:</span>
                <span class="value">{{ hedgePosition.sell }}克</span>
              </div>
              <div class="position-item sell">
                <span class="label">卖:</span>
                <span class="value">{{ hedgePosition.sell }}克</span>
              </div>
              <div class="position-item total">
                <span class="label">合计:</span>
                <span class="value">{{ hedgePosition.combined }}手</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 未对冲 -->
        <el-col :span="8">
          <el-card shadow="hover">
            <div slot="header">
              <span>未对冲</span>
            </div>
            <div class="unhedge-info">
              <div class="position-item buy">
                <span class="label">买:</span>
                <span class="value">{{ unHedgePosition.buy }}克</span>
              </div>
              <div class="position-item ratio">
                <span class="label">比例:</span>
                <span class="value">{{ unHedgePosition.ratio }}%</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 对冲账户和订单 -->
    <div
      class="account-panel"
      :class="{ 'card-margin': showHedgeBatch }"
      v-if="false"
    >
      <el-card shadow="hover" style="margin-right: 10px">
        <div slot="header">
          <span>对冲帐户</span>
        </div>
        <el-table
          :data="hedgeAccounts"
          size="mini"
          border
          style="width: 100%"
          :show-header="true"
          :show-summary="true"
          sum-text="合计"
          :summary-method="getSummaries"
          highlight-current-row
          @row-click="handleAccountRowClick"
        >
          <el-table-column
            prop="accountNo"
            label="帐号"
            width="100"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="netValue"
            label="净值"
            width="120"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="持仓"
            width="80"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span
                :class="scope.row.holding.startsWith('+') ? 'green' : 'red'"
              >
                {{ scope.row.holding.startsWith("+") ? "买" : "卖"
                }}{{ scope.row.holding.replace(/[+-]/g, "") }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="riskLevel"
            label="风险度"
            width="60"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="状态"
            width="50"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '正常' ? 'success' : 'danger'"
                size="mini"
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="hover" style="margin-right: 10px">
        <div slot="header">
          <span>对冲单</span>
        </div>
        <el-table
          :data="hedgeOrders"
          size="mini"
          border
          style="width: 100%"
          :show-header="false"
          :show-summary="false"
          highlight-current-row
        >
          <el-table-column
            prop="id"
            label="#"
            width="40"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="交易类型"
            width="40"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span :class="scope.row.type === '买' ? 'green' : 'red'">
                {{ scope.row.type }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            width="120"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.quantity }}
            </template>
          </el-table-column>
          <template slot="append">
            <div class="hedge-orders-summary">
              <div class="cell index">合计</div>
              <div class="cell type">{{ hedgeOrderNetSummary.dir }}</div>
              <div class="cell qty">
                <span>{{ hedgeOrderNetSummary.qtyText }}</span>
                <!-- 多冲操作按钮 -->
                <span
                  class="hedge-orders-summary-btn"
                  @click="handleHedgeAction"
                >
                  <i class="el-icon-caret-right"></i>
                </span>
              </div>
            </div>
          </template>
        </el-table>
      </el-card>
      <el-card shadow="hover" v-if="showHedgeBatch" style="margin-right: 10px">
        <!-- 对冲批次表格 - 点击操作按钮后显示 -->
        <div slot="header">
          <span>对冲批次</span>
        </div>
        <el-table
          :data="hedgeBatchOrders"
          size="mini"
          border
          style="width: 100%"
          :show-header="false"
        >
          <el-table-column width="40" align="center">
            <template slot-scope="scope">
              <span :class="scope.row.type === '买' ? 'green' : 'red'">
                {{ scope.row.type }}
              </span>
            </template>
          </el-table-column>
          <el-table-column width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.quantity }}
            </template>
          </el-table-column>
          <el-table-column width="40" align="center">
            <template slot-scope="scope"> {{ scope.row.lots }}手 </template>
          </el-table-column>
          <template slot="append">
            <div class="hedge-batch-summary">
              <div class="cell index">剩余</div>
              <div class="cell type"></div>
              <div class="cell qty-merged">
                {{ hedgeBatchSummary.totalLots }}手
              </div>
            </div>
          </template>
        </el-table>
      </el-card>
      <!-- 对冲面板 - 仅手动状态显示 -->
      <el-card shadow="hover" v-if="hedgeMode === 'manual' && showHedgeBatch">
        <div slot="header">
          <span>对冲面板(手动状态)</span>
        </div>

        <div class="hedge-content-manual">
          <!-- 对冲数据表格 -->
          <el-table
            :data="hedgePanelData"
            size="mini"
            border
            style="width: 100%; margin-bottom: 10px"
          >
            <el-table-column
              prop="accountNo"
              label="帐号"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="lots"
              label="手数"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  circle
                  @click="deleteHedgeData(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 底部输入表单 -->
          <div class="hedge-input-form">
            <el-form :model="hedgeForm" size="mini">
              <el-form-item>
                <el-input
                  v-model="hedgeForm.accountNo"
                  placeholder="输入账号"
                  @click="selectHedgeAccount"
                  size="mini"
                >
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="hedgeForm.price"
                  placeholder="输入价格"
                  size="mini"
                >
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="hedgeForm.lots"
                  placeholder="输入手数"
                  size="mini"
                >
                </el-input>
              </el-form-item>
            </el-form>
            <div class="hedge-input-form-btn">
              <el-button type="primary" @click="addHedgeData" size="mini">
                提交
              </el-button>
              <el-button type="success" @click="submitHedgeData" size="mini">
                确定
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 对冲账号选择对话框 -->
    <el-dialog
      title="选择对冲账号"
      :visible.sync="showAccountDialog"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-table
        :data="hedgeAccounts"
        size="mini"
        border
        style="width: 100%"
        @row-click="handleDialogAccountSelect"
        highlight-current-row
      >
        <el-table-column
          prop="accountNo"
          label="帐号"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="netValue"
          label="净值"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column label="持仓" width="80" align="center">
          <template slot-scope="scope">
            <span :class="scope.row.holding.startsWith('+') ? 'green' : 'red'">
              {{ scope.row.holding.startsWith("+") ? "买" : "卖"
              }}{{ scope.row.holding.replace(/[+-]/g, "") }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="riskLevel"
          label="风险度"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === '正常' ? 'success' : 'danger'"
              size="mini"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAccountDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAccountSelect">确定</el-button>
      </div>
    </el-dialog>

    <!-- 策略配置弹窗 -->
    <el-dialog
      title="策略配置"
      :visible.sync="showStrategyConfigDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="strategyConfigForm" label-width="80px">
        <el-row :span="24">
          <el-col :span="24">
            <el-form-item label="策略名称" prop="strategyName">
              <el-input
                v-model="strategyConfigForm.strategyName"
                placeholder="请输入策略名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                type="textarea"
                v-model="strategyConfigForm.description"
                placeholder="请输入策略描述"
                :rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="风险等级" prop="riskLevel">
              <el-select
                v-model="strategyConfigForm.riskLevel"
                placeholder="请选择风险等级"
              >
                <el-option label="低风险" value="low"></el-option>
                <el-option label="中风险" value="medium"></el-option>
                <el-option label="高风险" value="high"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="isActive">
              <el-switch
                v-model="strategyConfigForm.isActive"
                active-text="启用"
                inactive-text="禁用"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showStrategyConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="saveStrategyConfig">保存</el-button>
      </div>
    </el-dialog>

    <!-- 对冲面板 -->
    <!-- <div class="tree-panel">
			<el-card shadow="hover">
				<div slot="header">
					<span>对冲面板</span>
				</div>
				<el-table :data="flattenedTableData" border size="mini" :span-method="handleSpanMethod" :show-header="false" class="account-hierarchy-table">
					<el-table-column prop="level1" label="对冲单" align="center"></el-table-column>
					<el-table-column label="策略" align="center">
						<template slot-scope="scope">
							<div v-if="scope.row.level2" class="strategy-cell">
								<span>{{ scope.row.level2 }}</span>
								<el-tooltip class="item" effect="dark" content="策略配置" placement="top">
									<i class="el-icon-s-tools strategy-icon" @click="openStrategyConfig(scope.row)"></i>
								</el-tooltip>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="level3" label="终端" align="center"></el-table-column>
					<el-table-column prop="accountNo" label="账号" align="center"></el-table-column>
					<el-table-column prop="netValue" label="净值" align="center"></el-table-column>
					<el-table-column label="持仓" align="center">
						<template slot-scope="scope">
							<span v-if="scope.row.holding" :class="scope.row.holding.startsWith('+') ? 'green' : 'red'">
								{{ scope.row.holding.startsWith('+') ? '买' : '卖' }}{{ scope.row.holding.replace(/[+-]/g,
                                    '') }}
							</span>
						</template>
					</el-table-column>
					<el-table-column prop="riskLevel" label="风险度" width="80" align="center"></el-table-column>
					<el-table-column label="状态" width="80" align="center">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.status" :type="scope.row.status === '正常' ? 'success' : 'danger'" size="mini">
								{{ scope.row.status }}
							</el-tag>
						</template>
					</el-table-column>
				</el-table>
			</el-card>
		</div> -->

    <div class="tree-panel">
      <el-card shadow="hover">
        <div slot="header">
          <span>公共参数</span>
        </div>

        <!-- 思维导图组件 -->
        <top />
      </el-card>
    </div>

    <div class="tree-panel">
      <el-card shadow="hover">
        <div slot="header">
          <span>对冲面板</span>
        </div>

        <!-- 思维导图组件 -->
        <Tree :treeData="tableData" />
      </el-card>
    </div>

    <!-- 交易记录 带有告警音频 -->
    <div class="trade-record-panel">
      <el-card shadow="hover">
        <div slot="header">
          <span>交易记录/交易流水</span>
        </div>
        <!-- 隐藏的告警音频元素（确保路径在 public 根目录下，如 public/14141.wav → /14141.wav） -->
        <audio
          ref="alarmAudioEl"
          :src="alarmAudioUrl"
          preload="auto"
          style="display: none"
        ></audio>
        <div class="trade-controls">
          <el-form inline size="mini">
            <el-form-item label="状态过滤">
              <el-select
                v-model="tradeFilter.status"
                placeholder="全部"
                clearable
                style="width: 140px"
              >
                <el-option label="全部" :value="''"></el-option>
                <el-option label="成功" value="成功"></el-option>
                <el-option label="处理中" value="处理中"></el-option>
                <el-option label="异常" value="异常"></el-option>
                <el-option label="失败" value="失败"></el-option>
                <el-option label="超时" value="超时"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="simulateIncomingTrade"
                icon="el-icon-plus"
                >模拟交易</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-table
          :data="filteredTradeRecords"
          size="mini"
          border
          style="width: 100%"
          :row-class-name="tradeRowClassName"
        >
          <el-table-column
            prop="time"
            label="时间"
            width="160"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="orderId"
            label="单号"
            width="140"
            align="center"
          ></el-table-column>
          <el-table-column prop="side" label="方向" width="80" align="center">
            <template slot-scope="scope">
              <span :class="scope.row.side === '买' ? 'green' : 'red'">{{
                scope.row.side
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量(克)"
            width="100"
            align="right"
          ></el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            width="120"
            align="right"
          ></el-table-column>
          <el-table-column
            prop="terminal"
            label="终端"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="strategy"
            label="策略"
            width="120"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag :type="statusTagType(scope.row.status)" size="mini">{{
                scope.row.status
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="message"
            label="说明"
            align="left"
          ></el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getRechargeInfo } from "./api/recharge";
import Top from "./model/top.vue";
import Tree from "./model/tree.vue";
export default {
  components: {
    Top,
    Tree,
  },
  name: "HedgeWorkbench",
  data() {
    return {
      proplist: [
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
        {
          choose: false,
        },
      ],
      tableData: {
        id: 0,
        name: "对冲单",
        children: [
          {
            id: 1,
            date: "2016-05-02",
            name: "策略1",
            address: "上海市普陀区金沙江路 1518 弄",
            children: [
              {
                id: 11,
                date: "2016-05-02",
                name: "策略1-1",
                address: "上海市普陀区金沙江路 1518 弄",

                children: [
                  {
                    id: 11,
                    date: "2016-05-02",
                    name: "策略1-1",
                    address: "上海市普陀区金沙江路 1518 弄",
                  },
                  {
                    id: 12,
                    date: "2016-05-02",
                    name: "策略1-2",
                    address: "上海市普陀区金沙江路 1518 弄",
                  },
                ],
              },
              {
                id: 12,
                date: "2016-05-02",
                name: "策略1-2",
                address: "上海市普陀区金沙江路 1518 弄",
              },
            ],
          },

          {
            id: 3,
            date: "2016-05-01",
            name: "策略2",
            address: "上海市普陀区金沙江路 1519 弄",

            children: [
              {
                id: 31,
                date: "2016-05-01",
                name: "策略2-1",
                address: "上海市普陀区金沙江路 1519 弄",
              },
              {
                id: 32,
                date: "2016-05-01",
                name: "策略2-2",
                address: "上海市普陀区金沙江路 1519 弄",

                children: [
                  {
                    id: 311,
                    date: "2016-05-01",
                    name: "策略2-2-1",
                    address: "上海市普陀区金沙江路 1519 弄",
                  },
                  {
                    id: 322,
                    date: "2016-05-01",
                    name: "策略2-2-2",
                    address: "上海市普陀区金沙江路 1519 弄",
                  },
                ],
              },
            ],
          },
          {
            id: 4,
            date: "2016-05-03",
            name: "策略3",
            address: "上海市普陀区金沙江路 1516 弄",
          },
        ],
      },

      show: false,

      //
      connecting: false,
      startingTerminal: false,

      // 水贝金价状态 (1-5级)
      waterGoldStatus: 3,
      waterGoldPrice: "777.77",
      waterGoldSpread: "1.00",

      // 国际金价状态 (1-5级)
      internationalGoldStatus: 4,
      internationalGoldPrice: "320.00",
      priceDifference: "3.00",
      cnyPrice: "750.33",
      exchangeRate: "7.1023",
      recordRate: "7.1023",

      // 当前仓位
      currentPosition: {
        buy: "1326,534,100",
        sell: "3,520,126,300",
        total: "16101,254,800",
        netPosition: "16211277,000",
      },

      // 对冲仓位
      hedgePosition: {
        sell: "11,099,257,100",
        combined: "1353433.87",
      },

      // 未对冲
      unHedgePosition: {
        buy: "1024",
        ratio: "0.01",
      },

      // 表格列配置
      tableColumns: [
        { prop: "accountNo", label: "帐号", align: "center" },
        { prop: "netValue", label: "净值", align: "center" },
        { prop: "holding", label: "持仓", align: "center" },
        { prop: "riskLevel", label: "风险度", align: "center" },
        { prop: "status", label: "状态", align: "center" },
      ],

      // 对冲账户
      hedgeAccounts: [
        {
          accountNo: "1023475",
          netValue: "$725,133.05",
          holding: "+23.2",
          riskLevel: "15.00",
          status: "正常",
        },
        {
          accountNo: "1023476",
          netValue: "$1,234,567.89",
          holding: "-45.8",
          riskLevel: "22.50",
          status: "正常",
        },
        {
          accountNo: "1023477",
          netValue: "$890,123.45",
          holding: "+12.1",
          riskLevel: "18.75",
          status: "异常",
        },
        {
          accountNo: "1023478",
          netValue: "$567,890.12",
          holding: "-67.3",
          riskLevel: "25.30",
          status: "正常",
        },
      ],

      // 对冲单
      hedgeOrders: [
        { id: 1, type: "买", quantity: "1500克" },
        { id: 2, type: "卖", quantity: "2000克" },
      ],

      // 对冲批次配置
      hedgeBatchConfig: {
        isAuto: false,
      },

      // 控制对冲批次表格显示
      showHedgeBatch: false,

      // 对冲批次订单
      hedgeBatchOrders: [
        { id: 1, type: "卖", quantity: "3410克", lots: 1 },
        { id: 2, type: "买", quantity: "2000克", lots: 1 },
      ],

      // 对冲控制
      hedgeControl: {
        sell: "3110",
        lots: "1",
        accountNo: "1023475",
        orderLots: "1",
        platformSell: "1000",
      },

      tradingTerminalStatus: {
        isActive: false,
        isInitializing: false,
        lastUpdate: null,
        version: "v1.0.0",
      },
      systemLogs: [],
      stats: {
        messageQueueLength: 0,
      },
      // 对冲模式
      hedgeMode: "manual", // 对冲模式：manual-手动，auto-自动
      hedgePanelData: [], // 对冲面板数据
      hedgeForm: {
        accountNo: "", // 账号
        price: "", // 价格
        lots: "", // 手数
      },
      // 对冲账号选择对话框
      showAccountDialog: false,
      selectedHedgeAccount: null,

      // 策略配置弹窗
      showStrategyConfigDialog: false,
      currentStrategy: null,
      strategyConfigForm: {
        strategyName: "",
        description: "",
        riskLevel: "",
        isActive: true,
      },

      // 账户层级数据 - 四级结构：对冲单→策略→终端→账号
      accountTreeData: [
        {
          parentId: 0,
          Name: "对冲单",
          children: [
            {
              parentId: 100,
              Name: "策略1",
              children: [
                {
                  parentId: 1001,
                  Name: "终端A",
                  children: [
                    {
                      parentId: 10001,
                      Name: "账号1",
                      accountNo: "1023475",
                      netValue: "$725,133.05",
                      holding: "+23.2",
                      riskLevel: "15.00",
                      status: "正常",
                    },
                    {
                      parentId: 10002,
                      Name: "账号2",
                      accountNo: "1023476",
                      netValue: "$1,234,567.89",
                      holding: "-45.8",
                      riskLevel: "22.50",
                      status: "正常",
                    },
                  ],
                },
                {
                  parentId: 1002,
                  Name: "终端B",
                  children: [
                    {
                      parentId: 10003,
                      Name: "账号3",
                      accountNo: "1023477",
                      netValue: "$890,123.45",
                      holding: "+12.1",
                      riskLevel: "18.75",
                      status: "异常",
                    },
                  ],
                },
              ],
            },
            {
              parentId: 101,
              Name: "策略2",
              children: [
                {
                  parentId: 1003,
                  Name: "终端C",
                  children: [
                    {
                      parentId: 10004,
                      Name: "账号4",
                      accountNo: "1023478",
                      netValue: "$567,890.12",
                      holding: "-67.3",
                      riskLevel: "25.30",
                      status: "正常",
                    },
                    {
                      parentId: 10005,
                      Name: "账号5",
                      accountNo: "1023479",
                      netValue: "$1,234,567.89",
                      holding: "-45.8",
                      riskLevel: "22.50",
                      status: "正常",
                    },
                  ],
                },
              ],
            },
            {
              parentId: 102,
              Name: "策略3",
              children: [
                {
                  parentId: 1004,
                  Name: "终端D",
                  children: [
                    {
                      parentId: 10005,
                      Name: "账号5",
                      accountNo: "1023479",
                      netValue: "$1,234,567.89",
                      holding: "-45.8",
                      riskLevel: "22.50",
                      status: "正常",
                    },
                    {
                      parentId: 10006,
                      Name: "账号6",
                      accountNo: "1023480",
                      netValue: "$1,234,567.89",
                      holding: "-45.8",
                      riskLevel: "22.50",
                      status: "正常",
                    },
                    {
                      parentId: 10007,
                      Name: "账号7",
                      accountNo: "1023481",
                      netValue: "$1,234,567.89",
                      holding: "-45.8",
                      riskLevel: "22.50",
                      status: "正常",
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
      // 交易记录与告警
      tradeRecords: [
        {
          time: this.formatNow(),
          orderId: "T20250910-0001",
          side: "买",
          quantity: 1200,
          price: 777.12,
          terminal: "终端A",
          strategy: "策略1",
          status: "成功",
          message: "完成",
        },
        {
          time: this.formatNow(),
          orderId: "T20250910-0002",
          side: "卖",
          quantity: 800,
          price: 776.85,
          terminal: "终端B",
          strategy: "策略1",
          status: "异常",
          message: "对手方拒单",
        },
      ],
      tradeFilter: { status: "" },
      // 已取消音量控制，使用浏览器默认音量
      alarmEnabledStatuses: ["异常", "失败", "超时"],
      audioContext: null,
      audioUnlockAttempted: false,
      alarmAudioUrl: require("@/assets/14141.wav"),
      alarmAudio: null,
      audioUnlocked: false,

      // 思维导图根节点展开状态
    };
  },
  computed: {
    websocketState() {
      return this.$websocketState || {};
    },
    // 对冲单净头寸合计（供 append 区块和按钮使用）
    hedgeOrderNetSummary() {
      const data = this.hedgeOrders || [];
      let net = 0;
      data.forEach((item) => {
        const q = parseFloat(String(item.quantity).replace(/[克]/g, ""));
        if (!isNaN(q)) {
          if (item.type === "买") net += q;
          else if (item.type === "卖") net -= q;
        }
      });
      const dir = net > 0 ? "买" : net < 0 ? "卖" : "平";
      return {
        dir,
        qty: Math.abs(net),
        qtyText: `${Math.abs(net)}克`,
      };
    },
    // 对冲批次合计
    hedgeBatchSummary() {
      const data = this.hedgeBatchOrders || [];
      const totalLots = data.reduce((sum, item) => sum + (item.lots || 0), 0);
      return {
        totalLots,
      };
    },

    // 扁平化的表格数据 - 四级结构：对冲单→策略→终端→账号
    flattenedTableData() {
      const result = [];
      const treeData = this.accountTreeData[0]; // 获取对冲单数据

      treeData.children.forEach((strategy) => {
        if (strategy.children && strategy.children.length > 0) {
          // 有终端的情况
          strategy.children.forEach((terminal) => {
            if (terminal.children && terminal.children.length > 0) {
              // 有账户的情况
              terminal.children.forEach((account) => {
                result.push({
                  level1: result.length === 0 ? treeData.Name : "", // 只在第一行显示对冲单
                  level2:
                    account === terminal.children[0] &&
                    terminal === strategy.children[0]
                      ? strategy.Name
                      : "", // 只在第一个终端的第一个账户显示策略名
                  level3: account === terminal.children[0] ? terminal.Name : "", // 只在第一个账户显示终端名
                  accountNo: account.accountNo,
                  netValue: account.netValue,
                  holding: account.holding,
                  riskLevel: account.riskLevel,
                  status: account.status,
                  strategyIndex: treeData.children.indexOf(strategy),
                  terminalIndex: strategy.children.indexOf(terminal),
                  accountIndex: terminal.children.indexOf(account),
                });
              });
            } else {
              // 没有账户的终端
              result.push({
                level1: result.length === 0 ? treeData.Name : "",
                level2: terminal === strategy.children[0] ? strategy.Name : "",
                level3: terminal.Name,
                accountNo: "",
                netValue: "",
                holding: "",
                riskLevel: "",
                status: "",
                strategyIndex: treeData.children.indexOf(strategy),
                terminalIndex: strategy.children.indexOf(terminal),
                accountIndex: -1,
              });
            }
          });
        } else {
          // 没有终端的策略
          result.push({
            level1: result.length === 0 ? treeData.Name : "",
            level2: strategy.Name,
            level3: "",
            accountNo: "",
            netValue: "",
            holding: "",
            riskLevel: "",
            status: "",
            strategyIndex: treeData.children.indexOf(strategy),
            terminalIndex: -1,
            accountIndex: -1,
          });
        }
      });

      return result;
    },
    filteredTradeRecords() {
      const status = (this.tradeFilter.status || "").trim();
      if (!status) return this.tradeRecords;
      return this.tradeRecords.filter((r) => r.status === status);
    },
  },
  mounted() {
    this.initializeData();
    this.startStatusMonitoring();
    // this.getRechargeInfo();
    this.ensureAudioContext();
    // 监听首次用户交互以解锁 audio 播放
    window.addEventListener("click", this.unlockAudioOnce, {
      once: true,
      passive: true,
    });
  },
  beforeDestroy() {
    if (this.statusTimer) {
      clearInterval(this.statusTimer);
    }
    if (this.audioContext) {
      try {
        this.audioContext.close();
      } catch (e) {}
      this.audioContext = null;
    }
    window.removeEventListener("click", this.unlockAudioOnce);
  },
  methods: {
    onView() {
      this.show = true;
    },
    getRechargeInfo() {
      getRechargeInfo().then((res) => {
        console.log(112, "贵金属价格信息：", res);
      });
    },
    /**
     * 初始化数据
     */
    initializeData() {
      this.refreshStatus();
      this.generateMockData();

      // 添加示例对冲数据
      this.hedgePanelData = [
        { accountNo: "1023475", lots: "2" },
        { accountNo: "1023476", lots: "1" },
      ];

      // 调试信息
      console.log("对冲面板初始化完成");
      console.log("表单数据:", this.hedgeForm);
      console.log("对冲面板数据:", this.hedgePanelData);
      console.log("水贝金价:", this.waterGoldPrice);
    },

    /**
     * 开始状态监控
     */
    startStatusMonitoring() {
      this.statusTimer = setInterval(() => {
        this.updatePrices();
        this.updatePositions();
        this.addSystemLog("info", "系统状态正常");
      }, 5000);
    },

    /**
     * 获取连接状态文本
     */
    getConnectionStatusText() {
      if (this.websocketState.isConnected) return "已连接";
      if (this.websocketState.isReconnecting) return "重连中";
      return "未连接";
    },

    /**
     * 获取交易状态文本
     */
    getTradingStatusText() {
      if (this.tradingTerminalStatus.isActive) return "运行中";
      if (this.tradingTerminalStatus.isInitializing) return "初始化中";
      return "已停止";
    },

    /**
     * 更新价格数据
     */
    updatePrices() {
      // 模拟价格波动
      const waterChange = (Math.random() - 0.5) * 2;
      this.waterGoldPrice = (
        parseFloat(this.waterGoldPrice) + waterChange
      ).toFixed(2);

      const internationalChange = (Math.random() - 0.5) * 1;
      this.internationalGoldPrice = (
        parseFloat(this.internationalGoldPrice) + internationalChange
      ).toFixed(2);

      // 更新状态级别
      this.waterGoldStatus = Math.floor(Math.random() * 5) + 1;
      this.internationalGoldStatus = Math.floor(Math.random() * 5) + 1;
    },

    /**
     * 更新仓位数据
     */
    updatePositions() {
      // 模拟仓位变化
      const buyChange = Math.floor(Math.random() * 1000000);
      this.currentPosition.buy = (
        parseInt(this.currentPosition.buy.replace(/,/g, "")) + buyChange
      ).toLocaleString();

      const sellChange = Math.floor(Math.random() * 1000000);
      this.currentPosition.sell = (
        parseInt(this.currentPosition.sell.replace(/,/g, "")) + sellChange
      ).toLocaleString();
    },

    /**
     * 连接WebSocket
     */
    async connectWebSocket() {
      this.connecting = true;
      try {
        await new Promise((resolve) => setTimeout(resolve, 2000));
        this.addSystemLog("success", "WebSocket连接成功");
        this.$message.success("WebSocket连接成功");
      } catch (error) {
        this.addSystemLog("error", `WebSocket连接失败: ${error.message}`);
        this.$message.error(`连接失败: ${error.message}`);
      } finally {
        this.connecting = false;
      }
    },

    /**
     * 断开WebSocket
     */
    disconnectWebSocket() {
      this.addSystemLog("warning", "WebSocket连接已断开");
      this.$message.info("WebSocket已断开");
    },

    /**
     * 启动交易终端
     */
    async startTradingTerminal() {
      this.startingTerminal = true;
      try {
        await new Promise((resolve) => setTimeout(resolve, 3000));
        this.tradingTerminalStatus.isActive = true;
        this.tradingTerminalStatus.lastUpdate = new Date();
        this.addSystemLog("success", "交易终端启动成功");
        this.$message.success("交易终端启动成功");
      } catch (error) {
        this.addSystemLog("error", `交易终端启动失败: ${error.message}`);
        this.$message.error(`启动失败: ${error.message}`);
      } finally {
        this.startingTerminal = false;
      }
    },

    /**
     * 停止交易终端
     */
    stopTradingTerminal() {
      this.tradingTerminalStatus.isActive = false;
      this.tradingTerminalStatus.lastUpdate = new Date();
      this.addSystemLog("warning", "交易终端已停止");
      this.$message.info("交易终端已停止");
    },

    /**
     * 刷新状态
     */
    refreshStatus() {
      this.refreshStats();
      this.updatePrices();
      this.updatePositions();
      this.addSystemLog("info", "状态已刷新");
      this.$message.success("状态已刷新");
    },

    /**
     * 刷新统计信息
     */
    refreshStats() {
      if (this.$websocket && this.$websocket.getWebSocketStats) {
        this.stats = this.$websocket.getWebSocketStats();
      }
    },

    /**
     * 生成模拟数据
     */
    generateMockData() {
      this.addSystemLog("info", "系统初始化完成");
      this.addSystemLog("success", "所有服务启动成功");
    },

    /**
     * 添加系统日志
     */
    addSystemLog(level, message) {
      const log = {
        timestamp: new Date(),
        level,
        message,
      };

      this.systemLogs.unshift(log);

      if (this.systemLogs.length > 100) {
        this.systemLogs = this.systemLogs.slice(0, 100);
      }
    },

    /**
     * 计算表格合计行
     */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      // 固定5列的顺序：帐号、净值、持仓、风险度、状态
      sums[0] = "合计"; // 帐号列
      sums[1] = ""; // 净值列 - 计算总和
      sums[2] = ""; // 持仓列 - 计算总和
      sums[3] = ""; // 风险度列 - 计算平均值
      sums[4] = ""; // 状态列 - 不计算

      if (data && data.length > 0) {
        // 计算净值总和
        const netValueTotal = data.reduce((sum, item) => {
          const value = parseFloat(
            item.netValue.toString().replace(/[$,¥]/g, "")
          );
          return sum + (isNaN(value) ? 0 : value);
        }, 0);
        sums[1] = `$${netValueTotal.toLocaleString("en-US", {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`;

        // 计算持仓总和
        const holdingTotal = data.reduce((sum, item) => {
          const value = parseFloat(
            item.holding.toString().replace(/[+-]/g, "")
          );
          return sum + (isNaN(value) ? 0 : value);
        }, 0);
        sums[2] = holdingTotal.toFixed(1);

        // 计算风险度平均值
        const riskLevelAvg =
          data.reduce((sum, item) => {
            const value = parseFloat(item.riskLevel);
            return sum + (isNaN(value) ? 0 : value);
          }, 0) / data.length;
        sums[3] = riskLevelAvg.toFixed(2);
      }

      return sums;
    },

    /**
     * 计算对冲单表格合计行
     */
    getHedgeOrderSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      // 固定3列的顺序：#、交易类型、数量
      sums[0] = "合计"; // #列
      sums[1] = ""; // 交易类型列 - 计算净头寸
      sums[2] = ""; // 数量列 - 计算总数量

      if (data && data.length > 0) {
        // 计算净头寸（买-卖）
        let netPosition = 0;
        let totalQuantity = 0;

        data.forEach((item) => {
          const quantity = parseFloat(item.quantity.replace(/[克]/g, ""));
          if (!isNaN(quantity)) {
            totalQuantity += quantity;
            if (item.type === "买") {
              netPosition += quantity;
            } else if (item.type === "卖") {
              netPosition -= quantity;
            }
          }
        });

        // 设置交易类型列的合计（净头寸）
        if (netPosition > 0) {
          sums[1] = "买";
        } else if (netPosition < 0) {
          sums[1] = "卖";
        } else {
          sums[1] = "平";
        }

        // 设置数量列的合计
        sums[2] = `${Math.abs(netPosition)}克`;
      }

      return sums;
    },

    /**
     * 处理对冲操作按钮点击
     */
    handleHedgeAction() {
      // 使用计算属性的净头寸摘要
      const netText = this.hedgeOrderNetSummary.qtyText;
      const netDirection = this.hedgeOrderNetSummary.dir;

      // 显示对冲批次表格
      this.showHedgeBatch = true;

      // 根据对冲单的净头寸更新对冲批次表格
      this.updateHedgeBatchOrders(netDirection, this.hedgeOrderNetSummary.qty);

      this.$message.success(`对冲操作：净头寸 ${netText}`);
      console.log("执行对冲操作，净头寸：", netText);
    },

    /**
     * 处理对冲模式切换
     */
    handleHedgeModeChange(value) {
      this.$message.info(
        `对冲模式已切换为：${value === "auto" ? "自动" : "手动"}`
      );
      console.log("对冲模式切换：", value);

      // 如果切换到自动模式，清空手动输入的数据
      if (value === "auto") {
        this.hedgePanelData = [];
        this.hedgeForm = {
          accountNo: "",
          price: "",
          lots: "",
        };
      }
    },

    /**
     * 更新对冲批次订单
     */
    updateHedgeBatchOrders(direction, quantity) {
      // 清空现有订单
      this.hedgeBatchOrders = [];

      if (direction === "买" || direction === "卖") {
        // 添加新的对冲批次订单
        this.hedgeBatchOrders.push({
          id: 1,
          type: direction,
          quantity: `${quantity}克`,
          lots: Math.ceil(quantity / 1000), // 假设1手=1000克
        });
      }

      console.log("对冲批次订单已更新:", this.hedgeBatchOrders);
    },

    /**
     * 删除对冲数据
     */
    deleteHedgeData(index) {
      this.$confirm("确定删除该对冲数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.hedgePanelData.splice(index, 1);
        this.$message.success("对冲数据已删除");
        console.log("删除对冲数据:", this.hedgePanelData);
      });
    },

    /**
     * 添加对冲数据
     */
    addHedgeData() {
      if (!this.hedgeForm.accountNo || !this.hedgeForm.lots) {
        this.$message.warning("请填写账号和手数");
        return;
      }

      // 验证手数格式
      const lots = parseFloat(this.hedgeForm.lots);
      if (isNaN(lots) || lots <= 0) {
        this.$message.warning("请输入有效的手数");
        return;
      }

      this.hedgePanelData.push({
        accountNo: this.hedgeForm.accountNo,
        lots: this.hedgeForm.lots,
      });

      // 清空表单
      this.hedgeForm.lots = "";
      this.hedgeForm.price = "";
      this.hedgeForm.accountNo = "";

      this.$message.success("对冲数据已添加");
      console.log("添加对冲数据:", this.hedgePanelData);
    },

    /**
     * 提交对冲数据
     */
    submitHedgeData() {
      if (this.hedgePanelData.length === 0) {
        this.$message.warning("请至少添加一条对冲数据");
        return;
      }
      this.$message.success(
        `已提交 ${this.hedgePanelData.length} 条对冲数据到服务器`
      );
      console.log("提交对冲数据:", this.hedgePanelData);
    },

    /**
     * 选择对冲账号
     */
    selectHedgeAccount() {
      this.showAccountDialog = true;
      console.log("打开对冲账号选择对话框");
    },

    /**
     * 处理对冲账号选择对话框中的行点击
     */
    handleDialogAccountSelect(row) {
      this.selectedHedgeAccount = row;
      console.log("选择对冲账号:", row.accountNo);
    },

    /**
     * 确认选择对冲账号
     */
    confirmAccountSelect() {
      if (this.selectedHedgeAccount) {
        this.hedgeForm.accountNo = this.selectedHedgeAccount.accountNo;
        // this.hedgeForm.price = this.selectedHedgeAccount.netValue.replace(/[$,]/g, '').replace(/[.]/g, ''); // 自动填充价格
        this.showAccountDialog = false;
        this.$message.success(`已选择对冲账号: ${this.hedgeForm.accountNo}`);
        console.log("确认选择对冲账号:", this.hedgeForm.accountNo);
      } else {
        this.$message.warning("请选择一个对冲账号");
      }
    },

    /**
     * 处理对冲账户表格行点击
     */
    handleAccountRowClick(row) {
      this.hedgeForm.accountNo = row.accountNo;
      // this.hedgeForm.price = row.netValue.replace(/[$,]/g, '').replace(/[.]/g, ''); // 自动填充价格
      this.$message.success(`已选择对冲账号: ${row.accountNo}`);
      console.log("选择对冲账号:", row.accountNo);
    },

    /**
     * 打开策略配置弹窗
     */
    openStrategyConfig(row) {
      this.currentStrategy = row;
      this.strategyConfigForm = {
        strategyName: row.level2,
        description: "",
        riskLevel: "medium",
        isActive: true,
      };
      this.showStrategyConfigDialog = true;
      console.log("打开策略配置:", row.level2);
    },

    /**
     * 保存策略配置
     */
    saveStrategyConfig() {
      if (!this.strategyConfigForm.strategyName) {
        this.$message.warning("请输入策略名称");
        return;
      }

      this.$message.success(
        `策略 "${this.strategyConfigForm.strategyName}" 配置已保存`
      );
      console.log("保存策略配置:", this.strategyConfigForm);
      this.showStrategyConfigDialog = false;
    },

    /**
     * 处理表格单元格合并 - 四级结构
     */
    handleSpanMethod({ row, column, rowIndex, columnIndex }) {
      const data = this.flattenedTableData;

      // 对冲单列合并 - 只在第一行显示，合并所有行
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          return [data.length, 1]; // 合并所有行
        } else {
          return [0, 0]; // 其他行隐藏
        }
      }

      // 策略列合并 - 根据策略下的所有终端和账户数量合并
      if (columnIndex === 1) {
        if (row.level2) {
          // 计算该策略需要合并的行数
          let spanCount = 0;
          for (let i = rowIndex; i < data.length; i++) {
            if (data[i].strategyIndex === row.strategyIndex) {
              spanCount++;
            } else {
              break;
            }
          }
          return [spanCount, 1];
        } else {
          return [0, 0];
        }
      }

      // 终端列合并 - 根据终端下的账户数量合并
      if (columnIndex === 2) {
        if (row.level3) {
          // 计算该终端需要合并的行数
          let spanCount = 0;
          for (let i = rowIndex; i < data.length; i++) {
            if (
              data[i].strategyIndex === row.strategyIndex &&
              data[i].terminalIndex === row.terminalIndex
            ) {
              spanCount++;
            } else {
              break;
            }
          }
          return [spanCount, 1];
        } else {
          return [0, 0];
        }
      }

      // 其他列不合并
      return [1, 1];
    },
    // ============ 交易记录与告警 ============
    ensureAudioContext() {
      if (this.audioContext) return;
      const Ctx = window.AudioContext || window.webkitAudioContext;
      if (Ctx) {
        this.audioContext = new Ctx();
      }
    },
    ensureAlarmAudio() {
      if (!this.alarmAudio) {
        const el = this.$refs.alarmAudioEl;
        if (el) {
          this.alarmAudio = el;
          this.alarmAudio.addEventListener(
            "error",
            (e) => {
              console.warn("告警音频加载失败: ", e, "src=", this.alarmAudioUrl);
            },
            { once: true }
          );
          // 预加载
          try {
            this.alarmAudio.load();
          } catch (e) {}
        }
      }
    },
    unlockAudioOnce() {
      this.ensureAlarmAudio();
      if (!this.alarmAudio || this.audioUnlocked) return;
      try {
        this.alarmAudio.muted = true;
        this.alarmAudio
          .play()
          .then(() => {
            this.alarmAudio.pause();
            this.alarmAudio.currentTime = 0;
            this.alarmAudio.muted = false;
            this.audioUnlocked = true;
            console.log("音频已解锁");
          })
          .catch(() => {});
      } catch (e) {}
    },
    statusTagType(status) {
      switch (status) {
        case "成功":
          return "success";
        case "处理中":
          return "warning";
        case "异常":
          return "danger";
        case "失败":
          return "danger";
        case "超时":
          return "warning";
        default:
          return "";
      }
    },
    tradeRowClassName({ row }) {
      if (row.status === "异常" || row.status === "失败") return "row-danger";
      if (row.status === "超时") return "row-warning";
      return "";
    },
    triggerAlarmForStatus(status) {
      // 静音开关已移除，仅按状态判断
      if (!this.alarmEnabledStatuses.includes(status)) return;
      // 使用本地音频文件播放告警
      this.playAlarmAudio();
    },
    playAlarmAudio() {
      this.ensureAlarmAudio();
      if (!this.alarmAudio) return;
      try {
        this.alarmAudio.pause();
        this.alarmAudio.currentTime = 0;
      } catch (e) {}
      // 不再设置音量，使用系统/浏览器默认音量
      this.alarmAudio.play().catch((err) => {
        console.warn("音频播放被阻止或失败:", err);
      });
    },
    playBeepPattern(freqs, unitMs) {
      // 保留旧方法以备回退
      this.ensureAudioContext();
      const ctx = this.audioContext;
      if (!ctx) return;
      const now = ctx.currentTime;
      let t = now;
      const gain = ctx.createGain();
      gain.connect(ctx.destination);
      gain.gain.value = 0.2; // 固定音量
      freqs.forEach((f) => {
        if (f > 0) {
          const osc = ctx.createOscillator();
          osc.type = "sine";
          osc.frequency.value = f;
          osc.connect(gain);
          osc.start(t);
          osc.stop(t + unitMs / 1000);
        }
        t += unitMs / 1000;
      });
    },
    simulateIncomingTrade() {
      // 随机生成一条交易并触发告警
      const statuses = ["成功", "处理中", "异常", "失败", "超时"];
      const sides = ["买", "卖"];
      const status = statuses[Math.floor(Math.random() * statuses.length)];
      const side = sides[Math.floor(Math.random() * sides.length)];
      const newTrade = {
        time: this.formatNow(),
        orderId: `T${Date.now()}`,
        side,
        quantity: Math.floor(Math.random() * 3000) + 100,
        price: (
          parseFloat(this.waterGoldPrice) +
          (Math.random() - 0.5) * 5
        ).toFixed(2),
        terminal: ["终端A", "终端B", "终端C"][Math.floor(Math.random() * 3)],
        strategy: ["策略1", "策略2", "策略3"][Math.floor(Math.random() * 3)],
        status,
        message:
          status === "成功"
            ? "完成"
            : status === "处理中"
            ? "等待成交"
            : "需人工处理",
      };
      this.tradeRecords.unshift(newTrade);
      // 仅对最新一条触发告警
      this.triggerAlarmForStatus(status);
    },
    formatNow() {
      const d = new Date();
      const pad = (n) => (n < 10 ? "0" + n : "" + n);
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(
        d.getDate()
      )} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },
  },
};
</script>

<style scoped lang="scss">
.hedge-workbench {
  background-color: #f5f7fa;
  min-height: 100vh;
  overflow: hidden;
  // background-color: #f5f7fa;
  // height: 100vh; /* 限制高度为视窗高度 */
  // overflow-y: auto; /* 添加垂直滚动条 */
  // box-sizing: border-box;
}

/* 添加滚动条样式 */
// .hedge-workbench::-webkit-scrollbar {
//     width: 8px;
// }

// .hedge-workbench::-webkit-scrollbar-track {
//     background: #f1f1f1;
//     border-radius: 4px;
// }

// .hedge-workbench::-webkit-scrollbar-thumb {
//     background: #c1c1c1;
//     border-radius: 4px;
// }

// .hedge-workbench::-webkit-scrollbar-thumb:hover {
//     background: #a8a8a8;
// }

.status-panel {
  margin-bottom: 10px;

  .status-card {
    height: 100%;
    transition: all 0.3s ease;

    .flex-center {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 100%; // 确保内容占满整个卡片高度

      .status-header-title {
        margin: 0;
        color: #303133;
        font-weight: 600;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .status-content {
        display: flex;
        flex-direction: column;
        gap: 15px;
        align-items: center; // 居中对齐
        justify-content: center; // 垂直居中
      }
    }
  }
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: center;
}

.status-lights-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.status-lights {
  display: flex;
  gap: 6px;
  justify-content: center;
}

.status-light {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #dcdfe6;
  transition: all 0.3s ease;
  border: 2px solid #f0f0f0;
}

.status-light.active {
  background-color: #67c23a;
  box-shadow: 0 0 10px rgba(103, 194, 58, 0.6);
  border-color: #67c23a;
}

.light {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  border: 2px solid #fff;
}

.light.green {
  background-color: #67c23a;
  box-shadow: 0 0 18px rgba(103, 194, 58, 0.7);
}

.light.red {
  background-color: #f56c6c;
  box-shadow: 0 0 18px rgba(245, 108, 108, 0.7);
}

.light.yellow {
  background-color: #e6a23c;
  box-shadow: 0 0 18px rgba(230, 162, 60, 0.7);
}

.status-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  text-align: center;
}

.price-panel {
  margin-bottom: 10px;
}

.price-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  height: 100%; // 确保内容占满整个卡片高度
  align-content: center; // 多行内容垂直居中
}

.price-item {
  .label {
    color: #606266;
    font-weight: 500;
    min-width: 80px;
    flex-shrink: 0;
    margin-right: 10px;
  }

  .value {
    font-size: 16px;
    font-weight: 600;
    color: #409eff;
    flex: 1;
    text-align: right;
  }

  .cny-value {
    margin-left: 10px;
    color: #67c23a;
  }

  &:last-child {
    border-bottom: none;
  }
}

.position-panel {
  margin-bottom: 10px;

  .el-card {
    height: 140px; // 设置固定高度
  }
}

.position-info,
.hedge-position-info,
.unhedge-info {
  display: flex;
  flex-wrap: wrap;
  height: 100%; // 确保内容占满整个卡片高度
  align-content: center; // 多行内容垂直居中
  // padding: 10px 0; // 添加内边距

  .position-item {
    width: 50%;
    padding: 8px 0;
    display: flex; // 添加flex布局
    align-items: center; // 垂直居中对齐

    .label {
      color: #606266;
      font-weight: 500;
      margin-right: 10px;
    }

    .value {
      font-weight: 600;
    }
  }

  .buy {
    .value {
      color: #67c23a;
    }
  }

  .sell {
    .value {
      color: #f56c6c;
    }
  }

  .total {
    .value {
      color: #409eff;
    }
  }

  .net {
    .value {
      color: #e6a23c;
    }
  }
}

.account-panel {
  display: flex;
  margin-bottom: 10px;

  .el-card {
    height: 270px; // 减少固定高度
    padding-bottom: 0;

    .el-card__body {
      height: calc(100% - 60px); // 减去header高度
      display: flex;
      flex-direction: column;

      .el-table {
        flex: 1; // 表格占满剩余空间
      }
    }
  }
}

.card-margin {
  justify-content: space-between;
}

:deep(.el-card__header) {
  padding: 10px 16px !important;
}

:deep(.el-card__body) {
  padding: 14px 16px !important;
}

/* 优化mini尺寸表格的样式 */
:deep(.el-table--mini) {
  font-size: 12px;
  max-height: 200px;
  /* 限制表格最大高度 */
  overflow-y: auto;
  /* 添加表格内部滚动条 */
}

:deep(.el-table--mini .el-table__header-wrapper) {
  background-color: #f5f7fa;
}

/* 表格滚动条样式 */
:deep(.el-table--mini::-webkit-scrollbar) {
  width: 6px;
}

:deep(.el-table--mini::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.el-table--mini::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.el-table--mini::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

.hedge-content-manual {
  max-height: 200px;
  overflow-y: auto;
}

:deep(.el-table--mini .el-table__row) {
  height: 32px;
}

:deep(.el-table--mini .el-table__cell) {
  padding: 0px 0;
}

:deep(.el-table--mini .el-tag--mini) {
  height: 20px;
  line-height: 18px;
  font-size: 11px;
}

:deep(.el-table .cell.el-tooltip) {
  min-width: auto;
}

/* 持仓列颜色样式 */
:deep(.el-table .green) {
  color: #67c23a;
  font-weight: 600;
}

:deep(.el-table .red) {
  color: #f56c6c;
  font-weight: 600;
}

/* 自定义对冲单合计（append）区域样式，与表尾风格一致 */
.hedge-orders-summary {
  display: grid;
  grid-template-columns: 40px 40px 120px;
  justify-content: center;
  background: #f5f7fa;
}

.hedge-orders-summary .cell {
  padding: 6px 0;
  text-align: center;
  font-weight: 600;
  color: #303133;
}

.hedge-orders-summary .cell.index {
  color: #606266;
  border-right: 1px solid #ebeef5;
}

.hedge-orders-summary .cell.type {
  color: #606266;
  border-right: 1px solid #ebeef5;
}

.hedge-orders-summary-btn {
  width: 16px;
  height: 16px;
  line-height: 16px;
  background-color: #409eff;
  border-radius: 50%;
  display: inline-block;
  margin-left: 6px;
}

.hedge-orders-summary-btn i {
  color: #fff;
}

/* 对冲批次表格样式 */
.hedge-batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.hedge-batch-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

/* 对冲批次合计行样式 - 与表格列宽保持一致 */
.hedge-batch-summary {
  display: grid;
  grid-template-columns: 40px 80px 1fr;
  justify-content: center;
  background: #f5f7fa;
}

.hedge-batch-summary .cell {
  padding: 6px 0;
  text-align: center;
  font-weight: 600;
  color: #303133;
}

.hedge-batch-summary .cell.index {
  font-size: 12px;
  color: #606266;
}

.hedge-batch-summary .cell.type {
  font-size: 12px;
  color: #606266;
  border-right: 1px solid #ebeef5;
}

.hedge-batch-summary .cell.qty-merged {
  font-size: 12px;
  color: #606266;
  text-align: center;
}

/* 对冲模式控制样式 */
.hedge-mode-control {
  margin-bottom: 10px;
}

.hedge-mode-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.hedge-mode-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 对冲面板样式 */
.hedge-input-form {
  width: 100%;
}

.hedge-panel {
  margin-bottom: 10px;
}

.hedge-panel .el-card {
  height: auto;
}

// :deep(.el-form) {
//     display: flex;
//     align-items: center;
//     justify-content: space-between;
//     margin-bottom: 10px;
// }

// :deep(.el-button--mini.is-circle) {
//     padding: 4px;
// }

// :deep(.el-form-item__label) {
//     color: #606266;
//     line-height: 28px;
//     font-size: 12px;
//     padding: 0 4px;
// }

.hedge-input-form .el-form-item {
  margin-bottom: 0px;
  margin-right: 10px;

  &:last-child {
    margin-right: 0px;
  }
}

.hedge-input-form .el-input {
  min-width: 80px;
  max-width: 80px;
}

.hedge-input-form .el-button {
  margin-top: 2px;
}

/* 最小尺寸表单的特殊样式 */
.hedge-input-form .el-form--mini .el-form-item__label {
  padding-bottom: 4px;
}

.hedge-input-form .el-form--mini .el-input__inner {
  height: 28px;
  line-height: 28px;
}

/* 对冲账号选择对话框样式 */
.dialog-footer {
  text-align: right;
}

.hedge-input-form-btn {
  text-align: right;
}

/* 账户层级表格样式 */
.tree-panel {
  margin-bottom: 10px;
}

/* 思维导图样式 - 从左到右发散布局 */

.account-hierarchy-table {
  max-height: 400px;
  overflow-y: auto;
}

/* 表格滚动条样式 */
.account-hierarchy-table::-webkit-scrollbar {
  width: 6px;
}

.account-hierarchy-table::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.account-hierarchy-table::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.account-hierarchy-table::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 层级表格特殊样式 */
:deep(.account-hierarchy-table .el-table__cell) {
  padding: 8px 0;
  font-size: 12px;
}

:deep(.account-hierarchy-table .el-table__header-wrapper) {
  background-color: #f5f7fa;
}

:deep(.account-hierarchy-table .el-table__header th) {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
}

/* 合并单元格样式 */
:deep(.account-hierarchy-table .el-table__cell.is-center) {
  vertical-align: middle;
}

/* 持仓列颜色样式 */
:deep(.account-hierarchy-table .green) {
  color: #67c23a;
  font-weight: 600;
}

:deep(.account-hierarchy-table .red) {
  color: #f56c6c;
  font-weight: 600;
}

/* 策略单元格样式 */
.strategy-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  // gap: 8px;
}

.strategy-icon {
  // color: #409eff;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.3s ease;
  margin-left: 4px;
}

.strategy-icon:hover {
  color: #66b1ff;
}
.trade-record-panel {
  margin-top: 10px;
}

.trade-controls {
  margin-bottom: 8px;
}

:deep(.row-danger) {
  background-color: #fff5f5;
}

:deep(.row-warning) {
  background-color: #fff8e6;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item {
  background-color: #d3dce6;
}

.mb-item {
  padding: 0 10px;
}

.popover-box {
  width: 700px;
  padding: 10px;

  .setting-item {
    padding: 5px 10px;
    display: inline-flex;
    align-items: center;
    width: 33%;
    box-sizing: border-box;
  }
}
</style>
